package com.integral.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.integral.system.domain.SysUserDo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sysLogin")
public class LoginController {

    @PostMapping("/login")
    @ResponseBody
    public JSONObject login(@RequestBody Map<String,String> params){
        JSONObject json = new JSONObject();

        String userName = params.get("userName");
        String password = params.get("password");

        //获取用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        try {
            subject.login(token);
            json.put("code",200);
            json.put("msg","登录成功");
            SysUserDo user = (SysUserDo) subject.getPrincipal();
            json.put("userInfo",user);
        }catch (UnknownAccountException exception){
            json.put("code",500);
            json.put("msg","用户不存在");
        }catch (IncorrectCredentialsException exception){
            json.put("code",500);
            json.put("msg","用户名或密码错误");
        }
        return json;
    }
}
